<?php

namespace Haozing\FastCore\Context\Service;

class User
{
    private array $user = [];

    public function __construct(array $user = [])
    {
        $this->setUser($user);
    }

    public function setUser(array $user): self
    {
        $this->user = $user;
        return $this;
    }

    public function withUpdatedUser(array $updatedData): self
    {
        $new = new self($this->user);
        foreach ($updatedData as $key => $value) {
            $new->set($key, $value);
        }
        return $new;
    }

    public function get(string $key, mixed $default = null): mixed
    {
        return $this->user[$key] ?? $default;
    }

    public function set(string $key, mixed $value): self
    {
        $this->user[$key] = $value;
        return $this;
    }

    public function has(string $key): bool
    {
        return isset($this->user[$key]);
    }

    public function all(): array
    {
        return $this->user;
    }

    public function toJson(): string
    {
        return json_encode($this->user);
    }

    public static function fromJson(string $json): self
    {
        $data = json_decode($json, true);
        return new self($data);
    }
}